package com.gitee.ixtf.vertx.internal.converter

import com.gitee.ixtf.vertx.ParameterConverter
import io.vertx.core.buffer.Buffer
import io.vertx.core.eventbus.Message
import io.vertx.ext.web.RoutingContext

object Body2ByteArrayParameterConverter : ParameterConverter<ByteArray?> {
  private fun convertBody(body: Any?): ByteArray =
      when (body) {
        is String -> body.encodeToByteArray()
        is ByteArray -> body
        is Buffer -> body.bytes
        else -> throw RuntimeException()
      }

  override suspend fun convert(message: Message<*>) = message.body()?.let { convertBody(it) }

  override suspend fun convert(rc: RoutingContext) =
      rc.body()?.run { if (isEmpty) null else convertBody(buffer()) }
}
